// Logistics/InputDamage/InputDamage.js
/*{
单元名称：货损录入页面js
单元功能：选择销售单列出货物列表，录入货损数量，上传图片提交
所属模块功能：
创建人：yan
创建时间：230905
修改人：
修改时间：
}*/
let logisticsBehavior = require('../behavior/logistics')
Page({
  behaviors: [logisticsBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    orderid: '',

    activeTr: 0,

    field: [
      {type: 'picture',field_id: 'pic1',label: '照片1',picCount: 20},
    ],
    inputData:{
      jiedian: '货损'
    },

    // 照片列表
    picList: [],


  },
  components: {

  },
  //选择销售单
  selectSales(e){
    let {index} = e.currentTarget.dataset,
      {salesOrder} = this.data;
    // 选择销售单，获取货物列表，循环获取列表修改数量字段为0
    this.setData({
      activeTr: index,
    });
    this.getGoodsList(salesOrder[index].row_id);
  },
  //获取货物列表，id：运单管理明细表的行号
  getGoodsList(id){
    wx.showLoading({mask: true});
    let url = `WLAuth/ChuKuHuoWu/${id}`,
      post = {};
    wx.$get(5,url).then(res => {
      if (res.errcode != 0) return;
      wx.hideLoading();
      let data = res.data.row || [];
        this.setData({
          goodsList: data
        });
    })

  },

  // 货物列表数量修改
  bindipt(e){
    let {index} = e.currentTarget.dataset,
      {value} = e.detail;
    this.setData({
      [`goodsList[${index}].shuliang`]: value
    })
  },

  bindChange(e){
    let detail = e.detail,
      field = detail.field,
      id = field.field_id || field.fieldName,
      type = field.type,
      val = detail.val,
      val2 = '',
      obj = this.data.inputData;

    if (type === 'num' || type === 'currency' || type === 'percent'){
      val = val ? val : null
    }
    if (id === 'pic1'){
      let picList = val && val.split(',') || [];

      this.setData({picList})
    }

    //赋值
    this.data.inputData[id] = val;

  },


  //显示运输点
  onShowPoint(){// 开启验证
    this.data.validObj = {}
    this.setData({
      validFlag: !this.data.validFlag,
    });

    let formObj = this.data.inputData,
      validObj = this.data.validObj;
    this.validForm(validObj).then(valid => {
      if(valid) { // 表单验证通过
        console.log('表单验证通过', formObj);

        let {goodsList} = this.data,
          flag = true;
        try {
          goodsList.forEach(item =>{
            if (Number(item.shuliang)) {
              flag = false;
              throw 'break';
            }
          })
        }catch (e) {}
        if (flag){
          wx.$toast('请输入货损数量！');
          return
        }

        this.setData({showPoint: true})

      } else {  // 表单验证不通过
        console.log('表单验证不通过')
        wx.$toast('必填项不能为空！')
      }
    })
  },
  //确定选择
  onConfirmPoint(e){
    wx.showLoading({mask: true});
    this.submitDamage().then(res => {
      let {info} = e.detail
      this.submitFollow(info).then(flag => {
        if (flag){
          wx.$toast('提交成功');
          this.setData({showPoint: false});
        }
      })
    })

  },

  //提交货损
  submitDamage(){
    return new Promise(resolve => {
      let {goodsList,salesOrder,activeTr} = this.data,
        id = salesOrder[activeTr].row_id,
        arr = [];
      goodsList.forEach(item => {
        arr.push({
          "yundanhuowu_id": item.row_id,
          "huosunshuliang": item.shuliang

        })
      });
      let url = `WLAuth/HuoSun/${id}`;
      wx.$post(5,url,arr).then(res => {
        if (res.errcode != 0) return;
        resolve(res.data.row && res.data.row[0]);
      })
    })

  },
  //提交跟踪记录 info：运输点信息
  submitFollow(info){
    return new Promise(resolve => {
      let {orderid } = this.data,
        url1 = `WLAuth/GenZongJiLu`, //提交跟踪记录
        url2 = `WLAuth/HuoSunTuPian?yundanhao=${orderid}`; //提交货损照片

        let {picList} = this.data,
        pics = [];
      //循环把图片列表分成每5张图片一个数组
      for (let i = 0; i < picList.length; i += 5) {
        pics.push(picList.slice(i, i + 5));
      }
      let post1 = {
        "yundanhao": orderid,
        ...info,
      },post2 = {},
        zp = ['zhaopian','zhaopian2','zhaopia3','zhaopian4','zhaopian5'], //跟踪记录传入图片参数
        tp = ['tupian1','tupian2','tupian3','tupian4','tupian5']; //货损图片传入参数
      for (let i = 0;i < 5;i++){
        let val = pics[i] && pics[0].join(',') || '';
        post1[zp[i]] = val;
        post2[tp[i]] = val;
      }

      Promise.all([wx.$post(5,url1,post1),wx.$post(5,url2,post2)]).then(res => {
        console.log(res);
        let flag = true;
        res.forEach(item => {
          if (item.errcode != 0) flag = false;
        })
        resolve(flag);
      })
     /* wx.$post(5,url1,post1).then(res => {
        if (res.errcode != 0) return;
        resolve();
      })*/
    })
  },


  //切换显示货物信息
  toggleGoods(){
    this.setData({
      isShowGoods: !this.data.isShowGoods
    })
  },

  ready(){
    let {orderid} = this.data;
    wx.showLoading({mask: true})
    this.getSalesByOrder(orderid).then(res =>{
      if (res.length){
        this.getGoodsList(res[0].row_id);
      }else {
        wx.hideLoading();
      }
    });
    },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let {orderid} = options;
    if (!orderid) return;
    this.setData({orderid,});
    this.ready();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})
